package com.zhuyuan.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhuyuan.core.util.StringUtils;
import com.zhuyuan.database.base.BaseServiceImpl;
import com.zhuyuan.database.base.PageInfo;
import com.zhuyuan.security.service.UserDetailsImpl;
import com.zhuyuan.security.util.SecurityUtils;
import com.zhuyuan.system.api.domain.SysRole;
import com.zhuyuan.system.api.domain.SysUser;
import com.zhuyuan.system.api.domain.UserInfo;
import com.zhuyuan.system.mapper.SysUserMapper;
import com.zhuyuan.system.service.ISysDeptService;
import com.zhuyuan.system.service.ISysMenuService;
import com.zhuyuan.system.service.ISysRoleService;
import com.zhuyuan.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: 张琳凯
 * @Description: TODO
 * @DateTime: 2025/2/17 14:53
 **/
@RequiredArgsConstructor
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUser,SysUserMapper> implements ISysUserService {

    private final SysUserMapper userMapper;
    private final ISysRoleService sysRoleService;
    private final ISysMenuService sysMenuService;
    private final ISysDeptService sysDeptService;

    @Override
    public PageInfo<SysUser> queryUserList(Integer pageNum,Integer pageSize,SysUser sysUser) {
        Page<SysUser> page=new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<SysUser> wrapper= buildQueryWrapper(sysUser);
        Page<SysUser> sysUserPage = userMapper.selectPage(page,wrapper);
        return new PageInfo<SysUser>().setTotal(sysUserPage.getTotal()).setRows(sysUserPage.getRecords());
    }

    @Override
    public SysUser queryById(Long id) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(id);
        LambdaQueryWrapper<SysUser> wrapper= buildQueryWrapper(sysUser);
        return userMapper.selectOne(wrapper);
    }
    /**
     * 根据账号-用户名查询用户信息，适用于未登录的用户
     *
     * @param userName 账号
     * @return UserInfo
     */
    @Override
    public UserInfo queryByUserName(String userName) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        handlerQueryStatus(sysUser);
        return buildUserInfo(sysUser);
    }
    /**
     * 根据手机号查询用户信息，适用于未登录的用户
     *
     * @param phone 手机号
     * @return UserInfo
     */
    @Override
    public UserInfo queryByPhone(String phone) {
        SysUser sysUser = new SysUser();
        sysUser.setPhoneNumber(phone);
        handlerQueryStatus(sysUser);
        return buildUserInfo(sysUser);
    }
    /**
     * 根据当前用户查询用户信息，适用于已登录的用户
     * @return UserInfo
     */
    @Override
    public UserInfo getDetailInfo() {
        Long id=SecurityUtils.getUserId();
        SysUser sysUser=new SysUser();
        sysUser.setUserId(id);
        handlerQueryStatus(sysUser);
        return buildUserInfo(sysUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrUpdateUser(SysUser sysUser) {
        boolean isUpdate= sysUser.getUserId()!=null;
        UserDetailsImpl currentUser = SecurityUtils.getCurrentUser();
        int result=0;
        if (isUpdate){
            //更新
            SysUser oldSysUser = userMapper.selectById(sysUser.getUserId());
            if (!oldSysUser.getPassword().equals(sysUser.getPassword())){
                PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
                String newPassword = encoder.encode(sysUser.getPassword());
                sysUser.setPassword(newPassword);
            }
            sysUser.setUpdateBy(sysUser.getUserId().toString());
            sysUser.setUpdateTime(LocalDateTime.now());
            result=userMapper.updateById(sysUser);
        }else{
            //新增
            PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
            String encodePWD = passwordEncoder.encode(sysUser.getPassword());
            sysUser.setPassword(encodePWD);

            assert currentUser != null;
            sysUser.setCreateBy(currentUser.getUserId().toString());
            sysUser.setCreateTime(LocalDateTime.now());
            result=userMapper.insert(sysUser);
        }
        return result>0;
    }

    @Override
    public boolean deletedUser(Long id) {
        SysUser sysUser = userMapper.selectById(id);
        sysUser.setDelFlag(2);
        return userMapper.updateById(sysUser)>0;
    }

    /**
     * 处理查询条件，保证筛选是可用的账号和未删除的账号
     */
    private void handlerQueryStatus(SysUser sysUser){
        sysUser.setStatus(0);
        sysUser.setDelFlag(0);
    }

    private UserInfo buildUserInfo(SysUser sysUser){
        //获取用户信息
        LambdaQueryWrapper<SysUser> wrapper= buildQueryWrapper(sysUser);
        SysUser user = userMapper.selectOne(wrapper);
        if (user==null){
            return null;
        }
        Long id=user.getUserId();
        //是否是管理员
        boolean isAdmin = sysRoleService.hasSuperAdminByUid(id);
        //角色id列表
        List<String> roleIds = sysRoleService.getRoleIdsByUid(id);
        //角色列表
        SysRole sysRoleFilter=new SysRole();
        sysRoleFilter.setStatus("0");
        sysRoleFilter.getParams().put("roleIds", org.springframework.util.StringUtils.collectionToCommaDelimitedString(roleIds));
        List<SysRole> roles = sysRoleService.getRoles(sysRoleFilter);
        //部门id列表
        List<Long> deptAndSubIds = sysDeptService.queryDeptAndSubIds(user.getDeptId());
        //权限
        List<String> perms = sysMenuService.getPermTreeByUid(id);
        UserInfo userInfo=new UserInfo();
        userInfo.setUser(user);
        userInfo.setRoleIds(roleIds);
        userInfo.setRoles(roles);
        userInfo.setDeptAndSubIds(deptAndSubIds);
        userInfo.setPermissionList(perms);
        userInfo.setAdmin(isAdmin);
        return userInfo;
    }


    //构建筛选条件
    private LambdaQueryWrapper<SysUser> buildQueryWrapper(SysUser sysUser){
        LambdaQueryWrapper<SysUser> lqw = Wrappers.lambdaQuery();
        //用户id
        lqw.eq(sysUser.getUserId()!=null, SysUser::getUserId, sysUser.getUserId());
        //账户
        lqw.eq(sysUser.getUserName()!=null, SysUser::getUserName, sysUser.getUserName());
        //手机号
        lqw.eq(sysUser.getPhoneNumber()!=null, SysUser::getPhoneNumber, sysUser.getPhoneNumber());
        //部门id
        lqw.eq(sysUser.getDeptId()!=null, SysUser::getDeptId, sysUser.getDeptId());
        //昵称-用户名
        lqw.like(StringUtils.isNotBlank(sysUser.getNickName()), SysUser::getNickName, sysUser.getNickName());
        //账号状态
        lqw.eq(sysUser.getStatus()!=null, SysUser::getStatus, sysUser.getStatus());
        //性别
        lqw.eq(StringUtils.isNotBlank(sysUser.getSex()), SysUser::getSex, sysUser.getSex());
        return lqw;
    }
}
